import 'package:dio/dio.dart';
import 'package:duo_zui/constant/cache_key.dart';
import 'package:duo_zui/constant/constant.dart';
import 'package:duo_zui/model/model.dart';
import 'package:duo_zui/widget/BaseModuleWidget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert' as convert;

class MyHomePage extends StatefulWidget {
  User user;

  MyHomePage({Key key, this.user}):super(key: key);

  @override
  State<StatefulWidget> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  final List<String> list = ['动态', '文章', '其他'];

  TabController tabController;

  List<dynamic> feeds = [];

  int lastKey = 0;

  User myUser;

  @override
  void initState(){
    tabController = new TabController(length: list.length, vsync: this);
    this.myUser = widget.user;
    super.initState();
    getData();
  }

  void getUser() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    Map<String,dynamic> map = convert.jsonDecode(prefs.getString(CacheKey.User_CACHE)??'');
    myUser = User.fromJson(map);
  }

  void getData()async{
    if (lastKey == 1){
      feeds = [];//下拉刷新的时候将DataList制空
    }
    Dio dio = new Dio();
    Response response = await dio.get("http://www.appshuo.club/api/client/api/myArticle/all?uid=${myUser.id}&blog_id=all&type=1&page=1&pageSize=10");
    Reslut reslut = Reslut.fromJson(response.data);
    print(reslut.response.feeds.toString());
    if(!reslut.response.hasMore){
      return; //如果没有数据就不继续了
    }
    //lastKey = reslut.response.lastKey; //更新lastkey
    setState(() {
      getUser();
      feeds.addAll(reslut.response.feeds);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
      slivers: <Widget>[
        new SliverAppBar(
            floating: true,
            snap: true,
            pinned: true,
            expandedHeight: 250,
            flexibleSpace: FlexibleSpaceBar(
              title: Text('${myUser.nickname}'),
              background: Image.network(
                'http://img1.mukewang.com/5c18cf540001ac8206000338.jpg',
                fit: BoxFit.cover,
              ),
            ),
        ),
        SliverPersistentHeader(	// 可以吸顶的TabBar
          pinned: true,
          delegate: StickyTabBarDelegate(
            child: TabBar(
              labelColor: Colors.black,
              controller: this.tabController,
              tabs: <Widget>[
                Tab(text: '动态'),
                Tab(text: '文章'),
                Tab(text: '其他'),
              ],
            ),
          ),
        ),
        SliverFillRemaining(		// 剩余补充内容TabBarView
          child: TabBarView(
            controller: this.tabController,
            children: <Widget>[
              Center(child: Text('动态, 暂无数据~')),
              SafeArea(
                  child: ListView.builder(
                    itemBuilder: (BuildContext context, int index) {
                      return Column(
                        children: <Widget>[
                          Container(
                            child: getItem(feeds[index]),
                            padding: const EdgeInsets.only(
                                left: Constant.MARGIN_LEFT,
                                right: Constant.MARGIN_RIGHT),
                            color: Colors.white,
                          ),
                          Container(
                            height: 10.0,
                            color: Colors.transparent,
                          )
                        ],
                      );
                    },
                    physics: const ClampingScrollPhysics(),
                    itemCount: feeds.length,
                )
              ),
              Center(child: Text('其他, 暂无数据~')),
            ],
          ),
        ),
      ],
    ));
  }

  Widget getItem(feed) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      child: Container(
        child: Row(
          children: <Widget>[
            Container(
              width: MediaQuery.of(context).size.width-120,
              height: 120,
              margin: EdgeInsets.all(0),
              child: Column(
                children: <Widget>[
                  Container(
                    child: TitleLabel(context, feed.post.title),
                    //height: 90,
                    padding: const EdgeInsets.fromLTRB(10, 0, 10, 5),
                    alignment: Alignment.topLeft,
                  ),
                  Expanded(
                    child: Container(
                        padding: EdgeInsets.fromLTRB(10, 0, 10, 5),
                        alignment: Alignment.topLeft,
                        child: DescriptionLabel(context, feed.post.description == null ? '' : feed.post.description)
                    ),
                  )
                ],
              ),
            ),
            Expanded(
              child:  Container(
                margin: EdgeInsets.only(left: 0),
                // width: 120,
                // height: 120,
                alignment: Alignment.topCenter,
                child: Image.network(feed.image,width: 120,height: 120,),
              ),
            ),
          ],
        ),
      ),
      onTap: () {

      },
    );
  }
}

class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar child;

  StickyTabBarDelegate({@required this.child});

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return this.child;
  }

  @override
  double get maxExtent => this.child.preferredSize.height;

  @override
  double get minExtent => this.child.preferredSize.height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}